//
//  chartViewController.m
//  ViagemBem
//
//  Created by Rodrigo Morbach on 01/11/13.
//  Copyright (c) 2013 Michel de Sousa Carvalho. All rights reserved.
//

#import "chartViewController.h"
#import "Cidade.h"
#import "GastoDAO.h"
#import "TipoGasto.h"

@interface chartViewController ()
@property (nonatomic, strong) CPTGraphHostingView *hostView;
@property (nonatomic, strong) NSArray *dadosGasto;
@property (nonatomic, strong)     NSDecimalNumber *alimentacao;
@property (nonatomic, strong)     NSDecimalNumber *transporte;
@property (nonatomic, strong)     NSDecimalNumber *outros;
-(void)configureHost;
-(void)configureGraph;
-(void)configureChart;
-(void)configureLegend;



@end

@implementation chartViewController

@synthesize hostView = hostView_;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated{

    self.dataPieChart = [[NSDictionary alloc] init];
    self.dataPieChart = @{@"Alimentação":self.alimentacao,@"Transporte":self.transporte, @"Outros":self.outros};
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    float valorTransporte = 0;
    float valorAlimentacao = 0;
    float valorOutros = 0;
    float valor = 0;
    self.dadosGasto = [GastoDAO listarGastos:self.viagem];
    for(Gasto *a in self.dadosGasto){
        valor = [a.valor floatValue];
        if([a.tipoGasto.tipo isEqualToString:@"Transporte"]){
            valorTransporte += valor;
        }
        else if([a.tipoGasto.tipo isEqualToString:@"Alimentação"]){
            valorAlimentacao += valor;
        }
        if([a.tipoGasto.tipo isEqualToString:@"Outros"]){
            valorOutros += valor;
        }
        
    }
    self.alimentacao = [[NSDecimalNumber alloc]initWithFloat:valorAlimentacao];
    self.transporte = [[NSDecimalNumber alloc]initWithFloat:valorTransporte];
    self.outros = [[NSDecimalNumber alloc]initWithFloat:valorOutros];

    
    
}
-(void) viewDidAppear:(BOOL)animated{
       [self initPlot];
}
-(void)initPlot {
    [self configureHost];
    [self configureGraph:[[[@"De: " stringByAppendingString: self.viagem.cidadeOrigem.nome]stringByAppendingString:@" para: "]stringByAppendingString:self.viagem.cidadeDestino.nome]] ;
    [self configureChart];
    [self configureLegend];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

}
//Configura a subview para apresentação do gráfico
-(void)configureHost {
    self.hostView = [[CPTGraphHostingView alloc] initWithFrame:self.view.frame];
    [self.view addSubview: self.hostView];
}
//Inicializa um gráfico
-(void)configureGraph:(NSString*)tituloViagem {
	CPTGraph *graph = [[CPTXYGraph alloc] initWithFrame:self.hostView.bounds];
	self.hostView.hostedGraph = graph;
	graph.paddingLeft = 20.0f;
	graph.paddingTop = 40.f;
	graph.paddingRight = 20.0f;
	graph.paddingBottom = 20.0f;
	graph.axisSet = nil;
    //Estilo da fonte
	CPTMutableTextStyle *textStyle = [CPTMutableTextStyle textStyle];
	textStyle.color = [CPTColor blackColor];
	textStyle.fontName = @"Helvetica Neue";
	textStyle.fontSize = 16.0f;
    //Título do gráfico
	NSString *title = tituloViagem;
	graph.title = title;
	graph.titleTextStyle = textStyle;
	graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
	graph.titleDisplacement = CGPointMake(0.0f, -30.0f);

}

-(void)configureChart {
	CPTGraph *graph = self.hostView.hostedGraph;
	CPTPieChart *pieChart = [[CPTPieChart alloc] init];
	pieChart.dataSource = self;
	pieChart.delegate = self;
	pieChart.pieRadius = (self.hostView.bounds.size.width * 0.55) / 2;
	pieChart.identifier = graph.title;
	pieChart.startAngle = M_PI_4;
	pieChart.sliceDirection = CPTPieDirectionClockwise;
	// 3 - Create gradient
	CPTGradient *overlayGradient = [[CPTGradient alloc] init];
	overlayGradient.gradientType = CPTGradientTypeRadial;
	overlayGradient = [overlayGradient addColorStop:[[CPTColor redColor] colorWithAlphaComponent:0.0] atPosition:0.9];
	overlayGradient = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.4] atPosition:1.0];
	pieChart.overlayFill = [CPTFill fillWithGradient:overlayGradient];
	// 4 - Add chart to graph
	[graph addPlot:pieChart];
}
#pragma mark - CPTPlotDataSource methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
    
    return [[self.dataPieChart allKeys]count];
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
	if (CPTPieChartFieldSliceWidth == fieldEnum) {
        NSArray *keys = [self.dataPieChart allKeys];
        id aKey = [keys objectAtIndex:index];
        return [self.dataPieChart objectForKey:aKey];
}
	return [NSDecimalNumber zero];
}
//Cria a legenda para o gráficos
-(void)configureLegend {
    
	CPTGraph *graph = self.hostView.hostedGraph;
	
	CPTLegend *theLegend = [CPTLegend legendWithGraph:graph];
	
	theLegend.numberOfColumns = 1;
	theLegend.fill = [CPTFill fillWithColor:[CPTColor whiteColor]];
	theLegend.borderLineStyle = [CPTLineStyle lineStyle];
	theLegend.cornerRadius = 5.0;
	graph.legend = theLegend;
	graph.legendAnchor = CPTRectAnchorRight;
	CGFloat legendPadding = -(self.view.bounds.size.height / 5);
	graph.legendDisplacement = CGPointMake(legendPadding, -200.0);
}

-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index {
	// 1 - Define label text style
	static CPTMutableTextStyle *labelText = nil;
	if (!labelText) {
		labelText= [[CPTMutableTextStyle alloc] init];
		labelText.color = [CPTColor grayColor];
	}
    //Retorna as chaves do dicionário;
    NSArray *keys = [self.dataPieChart allKeys];
    id aKey = [keys objectAtIndex:index];
	//NSString *labelValue = keys[index];
    NSString *labelValue = [NSString stringWithFormat:@" R$%@", [self.dataPieChart objectForKey:aKey]];
    return [[CPTTextLayer alloc] initWithText:labelValue style:labelText];
}
//Retorna as legendas para o gráfico
-(NSString *)legendTitleForPieChart:(CPTPieChart *)pieChart recordIndex:(NSUInteger)index {
    NSArray *keys = [self.dataPieChart allKeys];
	NSString *labelLegend = keys[index];
    return labelLegend;
}

@end
